/*
 * @Date: 2022-06-11 21:29:14
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-04 17:36:23
 * @FilePath: \taro-music-learn\src\store\user\index.ts
 * @Description: user状态管理
 */
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getUserInfo, reqLogin, reqLogout, reqLikeVideoList } from "@/api/user";
import Taro from "@tarojs/taro";
import { reqUserMusicList } from "@/api/songs";
import {
  reqUserLikeMusicList,
  reqUserSubSingerList,
  reqSubVideoList
} from "@/api/user";
import { PromiseFormat } from "@/utils/request";
export interface UserState {
  isLogin: boolean;
  userInfo: any;
  collectionMusicList: Array<any>;
  ownMusciList: Array<any>;
  likeMusicList: Array<number>;
  subSingerList: Array<any>;
  subVideoList: Array<any>;
  likeVideoList: Array<any>;
}
//获取用户信息
export const fetchUserInfo = createAsyncThunk(
  "UserSlice/fetchUserInfo",
  async (_, thunkAPI) => {
    const { data } = await getUserInfo();
    console.log(data.profile !== null && data.code === 200, "请求条件");
    if (data.profile !== null && data.code === 200) {
      thunkAPI.dispatch(fetchUserMusicList());
      thunkAPI.dispatch(fetchUserLikeMusicList(data.profile.userId));
      thunkAPI.dispatch(fetchUserSubSingerList());
      thunkAPI.dispatch(fetchSubVideoList());
      thunkAPI.dispatch(fetchUserLikeVideoList());
      return Promise.resolve(data);
    } else {
      return Promise.reject(data);
    }
  }
);
//获取喜欢的音乐列表
export const fetchUserLikeMusicList = createAsyncThunk(
  "UserSlice/fetchUserLikeMusicList",
  async (id: number, thunkAPI) => {
    const { data } = await reqUserLikeMusicList(id);
    return PromiseFormat(data);
  }
);
//获取关注的歌手
export const fetchUserSubSingerList = createAsyncThunk(
  "UserSlice/fetchUserSubSingerList",
  async () => {
    const { data } = await reqUserSubSingerList();
    return PromiseFormat(data);
  }
);
//获取收藏的视频列表
export const fetchSubVideoList = createAsyncThunk(
  "UserSlice/fetchSubVideoList",
  async () => {
    const { data } = await reqSubVideoList();
    return PromiseFormat(data);
  }
);
//登录
export const fetchReqLogin = createAsyncThunk(
  "UserSlice/fetchReqLogin",
  async (
    paramaters: {
      username: string;
      password: string;
    },
    thunkAPI
  ) => {
    const { username: phone, password } = paramaters;
    const res = await reqLogin(phone, password);
    return PromiseFormat(res.data);
  }
);
//退出登录
export const fetchLogout = createAsyncThunk(
  "UserSlice/fetchLogout",
  async (_, thunkAPI) => {
    const res = await reqLogout();
    return PromiseFormat(res.data);
  }
);
//获取用户歌单（里面分收藏歌单和自己创建的歌单）
export const fetchUserMusicList = createAsyncThunk(
  "UserState/fetchUserMusicList",
  async (_, thunkAPI) => {
    console.log("发送收藏请求接口");
    const {
      User: { userInfo }
    } = thunkAPI.getState() as any;
    const res = await reqUserMusicList(userInfo.userId);
    return PromiseFormat(res.data);
  }
);
//获取用户点赞的视频
export const fetchUserLikeVideoList = createAsyncThunk(
  "UserState/fetchUserLikeVideoList",
  async () => {
    const { data } = await reqLikeVideoList();
    return PromiseFormat(data);
  }
);
const initialState: UserState = {
  isLogin: false,
  userInfo: {},
  collectionMusicList: [],
  ownMusciList: [],
  likeMusicList: [],
  subSingerList: [],
  subVideoList: [],
  likeVideoList: []
};
export const UserSlice = createSlice({
  name: "UserSlice",
  initialState,
  reducers: {},
  extraReducers: {
    //获取用户信息
    [fetchUserInfo.fulfilled.type]: (state, action) => {
      state.isLogin = true;
      state.userInfo = action.payload.profile;
    },
    [fetchUserInfo.rejected.type]: state => {
      state.isLogin = false;
      state.userInfo = {};
      Taro.removeStorageSync("cookies");
    },
    //登录接口
    [fetchReqLogin.fulfilled.type]: (state, action) => {
      Taro.setStorageSync("cookies", action.payload.cookie);
      state.isLogin = true;
      state.userInfo = action.payload.profile;
      Taro.atMessage({
        message: "登录成功",
        type: "success",
        duration: 2000
      });
      setTimeout(() => {
        Taro.navigateBack();
      }, 2000);
    },
    [fetchReqLogin.rejected.type]: state => {
      Taro.removeStorageSync("cookies");
      Taro.atMessage({
        message: "登录失败，账号或密码错误",
        type: "error"
      });
    },
    //退出登录
    [fetchLogout.fulfilled.type]: (state, action) => {
      state.userInfo = {};
      state.isLogin = false;
      state.collectionMusicList = [];
      state.ownMusciList = [];
      Taro.removeStorageSync("cookies");
    },
    //用户歌单以及收藏操作
    [fetchUserMusicList.fulfilled.type]: (state, action) => {
      state.ownMusciList = action.payload.playlist.filter((item: any) => {
        return item.subscribed === false;
      });
      state.collectionMusicList = action.payload.playlist.filter(
        (item: any) => {
          return item.subscribed === true;
        }
      );
    },
    [fetchUserMusicList.rejected.type]: state => {
      state.collectionMusicList = [];
      state.ownMusciList = [];
    },
    //获取用户喜欢的音乐列表
    [fetchUserLikeMusicList.fulfilled.type]: (state, action) => {
      state.likeMusicList = action.payload.ids;
    },
    //关注的歌手
    [fetchUserSubSingerList.fulfilled.type]: (state, action) => {
      state.subSingerList = [...state.subSingerList, ...action.payload.data];
    },
    //收藏的视频链接
    [fetchSubVideoList.fulfilled.type]: (state, action) => {
      state.subVideoList = action.payload.data;
    },
    //点赞的视频列表
    [fetchUserLikeVideoList.fulfilled.type]: (state, action) => {
      console.log("点赞列表", action.payload);
      state.likeVideoList = [
        ...state.likeVideoList,
        ...action.payload.data.feeds
      ];
    }
  }
});
